﻿using net_path.CSM.Common;
using net_path.CSM.plugins;
using ExcelConfig;
using FileSC.WEBService.Plugins;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TouchSocket.Core;
using TouchSocket.Http;
using TouchSocket.Sockets;

namespace net_path.CSM.Host
{
    public class WebHost : IWebHost
    {
        internal HttpService httpService { get; set; }
        public WebHost()
        {
            httpService = new HttpService();
        }
        public ServerState State { get { return httpService.ServerState; } }
        public async Task Start()
        {
            var allow_cors = AppConfig.Text("跨域请求") == "支持";
            var uris = AppConfig.Array("监听地址");
            var _iphosts = new Queue<IPHost>();
            foreach (var uri in uris)
            {
                if (AppConfig.YesOrNo("本地回环"))
                {
                    _iphosts.Enqueue(new IPHost($"127.{uri}"));
                    Console.WriteLine($"注册地址' 127.{uri}");
                }
                else
                {
                    _iphosts.Enqueue(new IPHost(uri));
                    Console.WriteLine($"注册地址' {uri}");
                }
            }
            try
            {
                httpService = new HttpService();
                await httpService.SetupAsync(new TouchSocketConfig()//加载配置
                     .SetListenIPHosts(_iphosts.ToArray())
                     .SetServerName("net-path#1.0")
                     .ConfigureContainer(a =>
                     {
                         //a.AddConsoleLogger();
                         if (allow_cors)
                         {
                             //添加跨域服务
                             a.AddCors(corsOption =>
                             {
                                 var cors_tag = AppConfig.Text("跨域名称");
                                 var cors_host = AppConfig.Text("跨域目标");

                                 //添加跨域策略，后续使用policyName即可应用跨域策略。
                                 corsOption.Add(cors_tag, corsBuilder =>
                                 {
                                     corsBuilder.AllowAnyMethod()
                                         .WithOrigin(cors_host).WithHeaders(HttpCommon.APPID, HttpCommon.APPKEY, HttpCommon.OID, HttpCommon.TOKEN, "content-type");
                                 });
                             });
                         }
                     })
                     .ConfigurePlugins(a =>
                     {
                         if (allow_cors)
                         {
                             var cors_tag = AppConfig.Text("跨域名称");
                             //应用名称为cors的跨域策略。
                             a.UseCors(cors_tag);
                         }

                         //此处添加插件逻辑，插件可以使用PluginBase类实现IHttpPlugin接口完成。
                         //这里使用委托直接完成
                         a.Add<TestPlug>();
                         a.Add<NetPathPlug>();

                         //default插件应该最后添加，其作用是
                         //1、为找不到的路由返回404
                         //2、处理header为Option的探视跨域请求。
                         a.UseDefaultHttpServicePlugin();
                     }));

                await httpService.StartAsync();
            }catch(Exception e)
            {
                Console.WriteLine(e.Message);
            }
            Console.WriteLine("授权服务: 已启动");
        }

        public async Task Stop()
        {
            await httpService.StopAsync();
            Console.WriteLine("授权服务: 已停止");
        }
    }
}
